<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
ini_set('max_execution_time', '0');
/*******************
 ***  读取远程123上速卖通的订单信息
 *** 2017/0804

 **********/
class AliexpressdataPro
{
    public function __construct()
    {
        $this->CI =& get_instance();
        $this->db1 = $this->CI->load->database('default', TRUE);
        $this->db2 = $this->CI->load->database('amazondata', TRUE);
		$this->CI->load->library('Amazondata');
        $this->amazondata=new amazondata();
    }
	//获取远程无忧交运信息
	public function aliexpresswuyou()
	{
		$this->CI->amazondata->returnaliexpresswuyou();
	}
	//用户取消订单
	private function doCancelOrder(){
		$sql = "SELECT * FROM db_aliexpress_ordertmp WHERE orderStatus = 'IN_CANCEL' AND cancel_flag = 0 ";
		$rs  = $this->db2->query($sql)->result_array();
		if(count($rs)>0){
			foreach($rs as $k=>$v){
				$sql_order = "SELECT * FROM db_order_list WHERE tradeid = '{$v['orderId']}' ";
				$rs_order  = $this->db1->query($sql_order)->row_array();
				//print_r($sql_order);exit;
				if($rs_order){
					//已支付或已配货状态
					if($rs_order['order_status']==2||$rs_order['order_status']==3){
						$this->db1->update('db_order_list',array('is_nodelivery'=>1)," order_id =".$rs_order['order_id']);
						//更新临时表
						$this->db2->update('db_aliexpress_ordertmp',array('cancel_flag'=>1)," id=".$v['id']);

						//更新日志记录
						$orderlog="";
						$orderlog["goods_id"] = $rs_order['order_id'];	//订单ID db_order_list
						$orderlog["updatetime"] = date("Y-m-d H:i:s");
						$orderlog["createUid"] = 0;
						$orderlog["types"] = 3;
						$orderlog["content"] = '禁止发货，客户取消订单,交易ID='.$rs_order['tradeid'];
						$orderlog["createUser"] ='auto';
						$this->db1->insert('db_goods_log', $orderlog);
					}
				}

			}
		}
	}
    //更新db_order_list db_order_sell
    public function doInsertOrderData(){

		$this->db2->limit(1);
		$row = $this->db2->get_where("db_aliexpress_ordertmp","flag=0 AND orderStatus = 'WAIT_SELLER_SEND_GOODS'")->result_array();
		if(count($row)==0)
		{
			$this->doCancelOrder(); //处理取消订单相关情况

			return false;
		}
		$rs = $row[0];
		
		$rorder = $this->db1->get_where("db_order_list","tradeid='".$rs["orderId"]."' AND shopid='".$rs["shopid"]."'")->result_array();
		if($rorder[0]["order_id"])
		{
			$this->db2->update("db_aliexpress_ordertmp",array("flag"=>2,"descr"=>'已同步系统成功'),"id='".$rs["id"]."' ");
			return $this->doInsertOrderData();
		}
		$exchange=$this->db1->get_where("d_moneyrate","name='".$rs["currencyCode"]."'")->result_array();
		$exchangerate=$exchange[0]["rate"]; 
		
		$arr_order_list="";
		$arr_order_list['order_sn'] = $this->CI->amazondata->getNo('Aliexpress',$rs['orderId']);//生成订单序号
		$arr_order_list['dates']  = date("Y-m-d"); //当天日期 判断order_sn使用
		$arr_order_list['ordertime']  = $rs['gmtCreate']; //订单日期时间
		$arr_order_list['order_source']  = "正常订单"; //默认
		$arr_order_list['customerid']  = $rs['buyerSignerFullname']; //客户id
		$arr_order_list['consignee']  =$rs['contactPerson']; //收货人
		$arr_order_list["order_status"] =2;
		$arr_order_list['shipping_status']=0;
		
		if($rs['country']=="")
		{
			$rscountry = $this->db1->get_where("d_country","countryid='".$rs['country_code']."'")->result_array();
			if($rscountry[0]["id"]){
				$rs["country_cn"] = $rscountry[0]["countrynameen"];
				$rs["country"] = $rscountry[0]["countrynamecn"];
			}
		}
		
		
		$arr_order_list['country']  = $rs['country']; //国家
		$arr_order_list['country_code']  = $rs['country_code']; //国家
		$arr_order_list['country_cn']  = $rs['country_cn'];
		$arr_order_list['province']  = addslashes($rs['province']);
		$arr_order_list['city']  = addslashes($rs['city']);
		$arr_order_list['address']  = addslashes($rs['address2']);
		$arr_order_list['address2']  =addslashes($rs['address']);
		$arr_order_list['zipcode']  = $rs['zip'];
		$arr_order_list['tel']  = $rs['mobileNo'];
		$arr_order_list['mobile']  = $rs['phoneNumber'];
		$arr_order_list['shopid']  = $rs['shopid']; //店铺id
		$arr_order_list['shopname']  = $rs['shopname'];
	    if(!$rs['shopoper']){
		    $sql_shop = "SELECT * FROM d_shop WHERE id = '{$rs['shopid']}' ";
		    $rs_shop  = $this->db1->query($sql_shop)->row_array();
		    $arr_order_list['shopoper']  = $rs_shop['updateoper'];//店铺负责人
	    }else{
		    $arr_order_list['shopoper']  = $rs['shopoper'];//店铺负责人
	    }

		$arr_order_list['moneytype']  = $rs['currencyCode'];//货币类型
		$arr_order_list['tradeid']  = $rs['orderId']; //交易单号
		
		$order_amount = $rs['goods_originask'] - $rs['shipping_originask'];//速卖通订单下载下来的是总金额，商品金额需要减运费
		$arr_order_list['goods_originask']  = $order_amount; //订单商品金额
		$arr_order_list["goods_amount"] =round($order_amount*$exchangerate,2);
		$arr_order_list['shipping_originask']  = $rs['shipping_originask']; //原始快递费
		$arr_order_list['shipping_fee']  = round($rs['shipping_originask']*$exchangerate,2);//物流费 人民币
		$arr_order_list['add_time'] = time();
		$arr_order_list['saleschannel']  = 'Aliexpress';
		$arr_order_list['pay_fee']  = round($rs['goods_originask']*0.015*$exchangerate,2);//支付费用
		$arr_order_list['pack_fee']='';
		$arr_order_list['platform_fee']= round($rs['goods_originask']*0.1*$exchangerate,2);//平台费用
		$arr_order_list['platform_message']  = $rs['remark']? $rs['remark']:''; //备注
		$arr_order_list['postageservice']  = $rs['postageservice']; //自选物流
		$arr_order_list["paypalmail"]='';

		$rshop = $this->db1->get_where("d_shop","name='".$rs["shopname"]."'")->result_array();
		$arr_order_list['platformID']  = $rshop[0]['platfrom'];//平台
		$exchange=$this->db1->get_where("d_moneyrate","name='".$rs["currencyCode"]."'")->result_array();
		$arr_order_list['moneyrate']  = $exchange[0]["rate"];//汇率
		
	
		$this->db1->trans_begin();	//事务开始
		$this->db1->insert("db_order_list",$arr_order_list);
		$orderID = $this->db1->insert_id();

		//更新日志记录
		$imgdata="";
		$imgdata["goods_id"] = $orderID;	//订单ID db_order_list
		$imgdata["updatetime"] = date("Y-m-d H:i:s");
		$imgdata["createUid"] = 0;
		$imgdata["types"] = 3;
		$imgdata["content"] = '速卖通接口自动新增订单,交易ID='.$rs['orderId'];
		$imgdata["createUser"] ='auto';
		$this->db1->insert('db_goods_log', $imgdata);

			$rsdbsellst = $this->db2->get_where("db_aliexpress_ordertmpsell"," tmpID='".$rs["id"]."'")->result_array();
			 foreach($rsdbsellst as $key=>$rsdbsell){
				unset($goods_name);
					
					 if($rsdbsell['skuCode']){

						$rgoods = $this->db1->get_where("db_goods","goods_sku='{$rsdbsell[skuCode]}' or cognatelist like '%,{$rsdbsell[skuCode]},%'")->result_array(); 
						if(empty($rgoods))
						{
							$Status=7;
							$goods_id = 0;
							$sweight = 0;
							$weight = 0;
							$goods_sn = $rsdbsell['skuCode'];
							$costprice = 0;
						}else{
							$factorycode = $this->factorycode();
							$Status=2;
							$goods_id = $rgoods[0]["goods_id"];
							$sweight = $rsdbsell["productCount"] * $rgoods[0]["g_weight"];
							$weight = $weight+$sweight;
							$goods_sn = $rgoods[0]["goods_sku"];
							if(is_numeric($goods_sn) && preg_match('|^\d{8}$|',$goods_sn))	//数字并且8位SKU并且11 12开头
							{
								$goodscode  = substr($goods_sn,0,2);//取开头2位数
								if(in_array($goodscode,$factorycode))	//是否存在在工厂code
								{
									$costprice = $rgoods[0]["g_costprice"];	//定制衣服按成本价计算
								}
							}else{
								//如果当前SKU不是8位，查询父SKU是不是8位并且11，12开头
								if(is_numeric($rgoods[0]["goods_parent_sku"]) && preg_match('|^\d{8}$|',$rgoods[0]["goods_parent_sku"]))	//数字并且8位SKU并且11 12开头
								{
									$goodscodes  = substr($rgoods[0]["goods_parent_sku"],0,2);//取开头2位数
									if(in_array($goodscodes,$factorycode))	//是否存在在工厂code
									{
										$costprice = $rgoods[0]["bulkprice"];	//批量按关联价计算
									}
								}else{
									$costprice = $rgoods[0]["g_costprice"];
								}
							}
							$goods_sn = $rgoods[0]["goods_sku"];
							$goods_name =  $rgoods[0]["goods_name"];
						}
					}else{
					
							$Status=7;
							$goods_id = 0;
							$sweight = 0;
							$weight = 0;
							$goods_sn = $rsdbsell['skuCode'];
							$costprice = 0;
				}
					
					$postsell = "";
					$postsell["order_id"] = $orderID;
					$postsell["goods_id"] = $goods_id;
					$postsell["goods_name"] = $goods_name?$goods_name:addslashes($rsdbsell['productName']);
					$postsell["goods_sn"] = $goods_sn;
				    if(!$costprice){
					    $costprice = 0;
				    }
					$postsell["costprice"] = $costprice;
					$postsell["goods_number"] = $rsdbsell["productCount"];
					$postsell["goods_price"] = $rsdbsell["originsellprice"]*$exchangerate;
					$postsell["goods_weight"]=$weight;
					$postsell["product_link"]=$rsdbsell["productSnapUrl"];
					$postsell["productId"]=$rsdbsell["productId"];
					$postsell["goods_amount"] = $rsdbsell["originsellprice"]*$rsdbsell["productCount"]*$exchangerate;
					$postsell["originsellprice"] = $rsdbsell["originsellprice"];
					$postsell["originsku"] = $rsdbsell["skuCode"];
					$this->db1->insert("db_order_sell",$postsell);
					if($goods_id==0)
					{
						$this->db1->update("db_order_list",array("order_status"=>7),"order_id=".$orderID);
					}
					if($weight)
					{
						$this->db1->update("db_order_list",array("orderweight"=>$weight),"order_id=".$orderID);
					}
					$this->db2->update("db_aliexpress_ordertmp",array("flag"=>2,"descr"=>'已同步系统成功')," id ='".$rs["id"]."'");
				 }
					if ($this->db1->trans_status() === FALSE)
					{
						$this->db1->trans_rollback();
					}
					else
					{
						$this->db1->trans_commit();
					}

				
		return $this->doInsertOrderData();

    }
	
	/**********回传单号********/
	public function createSendGoodsOrderOnline()
	{
		$sql_shop = "select GROUP_CONCAT(id) as shopid FROM d_shop where  platfrom = 10 AND agent_visit = 1 ";
        $rs_shop = $this->db1->query($sql_shop)->result_array();
		$shopid =  $rs_shop[0]['shopid'];
		 //获取所有订单列表
        $where = " WHERE (order_status = 4 or order_status = 5) AND is_update_platform = 0 "; //4为已发货状态 is_update_platform为未与线上同步
        $where .= " AND shipping_name is not null AND shipping_number is not null ";
		$where .=" AND shopid in ($shopid)";

        $sql_mabangorder = "SELECT order_id,shipping_name,shopid,shopname,tradeid,shipping_number,shipping_id FROM db_order_list ".$where;
        $rs_mabangorder = $this->db1->query($sql_mabangorder)->result_array();
		
	
		if(count($rs_mabangorder)>0)
		{
			foreach($rs_mabangorder as $key=>$rs)
			{
				 if($rs['shipping_name']=="中邮上海挂号小包"){
					 $rs['shipping_name'] = "中邮小包挂";
                }
				$sql_key = "SELECT * FROM db_order_express WHERE name = '{$rs['shipping_name']}' ";
                $rs_key = $this->db1->query($sql_key)->row_array();
				$rs_mabangorder[$key]['aliexpress_express'] = $rs_key['aliexpress_express'];
				
			}
			
			foreach($rs_mabangorder as $key=>$rs)
			{
				
				$row = $this->db2->get_where("db_aliexpress_update","shopid='".$rs["shopid"]."' AND tradeid = '".$rs["tradeid"]."'")->result_array();
				if(count($row)==0)
				{
					$postsell="";
					$postsell["order_id"] = $rs["order_id"];
					$postsell["shipping_name"] = $rs["shipping_name"];
					$postsell["shopid"] = $rs["shopid"];
					$postsell["shopname"] = $rs["shopname"];
					$postsell["tradeid"] = $rs["tradeid"];

					$postsell["shipping_number"] = $rs["shipping_number"];
					$postsell["shipping_id"] = $rs["shipping_id"]?$rs["shipping_id"]:0;
					$postsell["aliexpress_express"] = $rs["aliexpress_express"];
					$postsell["isupdate"] = 1;
					$postsell["updatetime"] = date("Y-m-d H:i:s");
					$postsell["message"] ="等待更新到速卖通平台";
					$this->db2->trans_begin();	//事务开始
					
					$this->db2->insert("db_aliexpress_update",$postsell);
					$this->db1->update("db_order_list",array("is_update_platform"=>'1'),"order_id=".$rs['order_id']);	//不再更新
					$log='';
					$log['orderId']=$rs['order_id'];
					$log['updateTime']=date('Y-m-d H:i:s');
					$log['shippingName']=$rs['aliexpress_express'];
					$log['shippingNumber']=$rs["shipping_number"];
					$log['types']='aliexpress';
					$log['content']='自动同步物流信息'.$response;
					$this->db1->insert("db_onlineshop_log",$log);

					$imgdata = "";
					$imgdata["goods_id"] = $rs['order_id'];	//订单ID
					$imgdata["updatetime"] = date("Y-m-d H:i:s");
					$imgdata["createUid"] = 0;
					$imgdata["types"] = 3;
					$imgdata["content"] = '自动同步物流信息,物流名称'.$rs['shipping_name'].'物流单号='.$rs["shipping_number"];
					$imgdata["createUser"] ='auto';
					$this->db1->query($this->db1->insert_string('db_goods_log', $imgdata));
					if ($this->db2->trans_status() === FALSE)
					{
						$this->db2->trans_rollback();
					}
					else
					{
						$this->db2->trans_commit();
					}
				}
			
		

			}
		}
	}

	
	public function factorycode()
	{
		$rsdb = $this->db1->get_where("db_factory","code >0")->result_array();
		foreach($rsdb as $key =>$rs)
		{
			$factorycode[] = $rs["code"];	//工厂编号
		}
		return $factorycode;
	}
}